import mongoose from 'mongoose';

export default defineNitroPlugin((nitroApp) => {
  nitroApp.hooks.hook('request', (event) => {
    event.context.reqStartTime = Date.now();
    event.context.clientIP = getRequestIP(event);

    // 只有使用了数据库时才检查数据库连接
    if (process.env.NUXT_NEED_DATABASE === 'true' && mongoose.connection.readyState !== 1) {
      throw createError({
        statusCode: 500,
        statusMessage: 'Database connection not established',
      });
    }
  });
});
